package com.itheima.boot.controller;

import com.itheima.boot.domain.Book;
import com.itheima.boot.domain.R;
import com.itheima.boot.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/books")
public class BookController {

    @Autowired
    private BookService bookService;

    /**
     * 条件查询
     *
     * @param book
     * @return
     */
    @GetMapping
    public R<Book> selectByCondition(Book book) {

        Book books = bookService.selectByCondition(book);
        if (books == null) {
            return R.error("查询的书籍不存在");
        }
        return R.success(books);
    }

    /**
     * 添加
     *
     * @param book
     * @return
     */
    @PostMapping
    public R<Book> addBook(@RequestBody Book book) {

        boolean flag = bookService.addBook(book);
        if (flag) {
            return R.success();
        }
        return R.error();
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public R<Book> deleteById(@PathVariable Integer id) {
        boolean flag = bookService.deleteById(id);
        if (flag) {
            return R.success();
        }
        return R.error();
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Book> selectById(@PathVariable Long id){
        Book book = bookService.selectById(id);
        return R.success(book);
    }

    /**
     * 修改
     * @param book
     * @return
     */
    @PutMapping
    public R<Book> updateBook(@RequestBody Book book){

        R<Book> reBook = selectById(book.getId());
        Book data = reBook.getData();

        boolean flag = bookService.updateBook(data);
        if (flag) {
            return R.success();
        }
        return R.error();
    }



}
